<template>
  <div class="roles">
    <!-- 面包屑头 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary">添加角色</el-button>
      <el-table :data="rolesList">
        <el-table-column type="expand" label="展开">
          <template #default="scope">
            <el-row
              v-for="item1 in scope.row.children"
              :key="item1.id"
              class="expand-row vcenter"
            >
              <el-col :span="5">
                <el-tag closable @close="closeTag(scope.row, item1.id, '1')">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-arrow-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="{ 'expand-row': i2 != item1.children.length - 1 }"
                  class="vcenter"
                >
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="closeTag(scope.row, item2.id, '2')"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-arrow-right"></i>
                  </el-col>
                  <el-col :span="14">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="closeTag(scope.row, item3.id, '3')"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="索引"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button icon="el-icon-edit" size="mini" type="primary"
              >编辑</el-button
            >
            <el-button icon="el-icon-delete" size="mini" type="danger"
              >删除</el-button
            >
            <el-button
              icon="el-icon-setting"
              size="mini"
              type="warning"
              @click="allocateRights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限按钮点击的对话框 -->
    <el-dialog title="分配权限" :visible.sync="isVisiable" width="50%">
      <!-- 这里的id是每个rightslist下面元素的id,以及children下面的id来标识自己 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        default-expand-all
        show-checkbox
        :default-checked-keys="checkList"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisiable = false">取 消</el-button>
        <el-button type="primary" @click="confirmAllocate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  created() {
    this.getRolesList();
  },
  data() {
    return {
      rolesList: [],
      isVisiable: false, //分配权限按钮的对话框的显示
      //获取到的权限列表
      rightsList: [],
      //树形结构定义了树形控件接受的数据在哪个字段里 接收的array数据 然后label表示需要的展示的叶子的名字在哪个字段 ,children代表嵌套的在哪个字段里
      treeProps: {
        label: "authName",
        children: "children"
      },
      checkList: [], //默认选择的权限结点的数组
      roleId: ""
    };
  },
  methods: {
    getRolesList() {
      this.$http.get("roles").then(res => {
        if (res.data.meta.status == 200) {
          this.rolesList = res.data.data;
          console.log(this.rolesList);
        } else {
          this.$message.error("获取角色列表失败");
        }
      });
    },
    closeTag(role, id, flag) {
      this.$confirm("确定删除吗", "注意", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(res => {
          if (res == "confirm" && res) {
            this.$http
              .delete(`roles/${role.id}/rights/${id}`)
              .then(res => {
                if (res.data.meta.status == 200) {
                  //将这个用户的权限刷新
                  // 单个role指的是那一行数据 children是指表格下拉菜单下的数据
                  console.log(flag);
                  role.children = res.data.data;
                  this.$message.success("删除成功");
                  //另外还需要做判断 如果三级权限被删光 则对应的二级权限也要删除 或者二级权限全部删光则一级权限也要删除
                  //二级
                  // if(flag == '2'){
                  //   let secRole = role.chilren.findIndex(item=>{
                  //   return item.id = id
                  // })
                  // if(role.children[secRole].children.length == 0){
                  //   role.children.splice(secRole,1)
                  // }
                  // }else if(flag =='3'){
                  //   let thiRole = role.children.
                  // }
                } else {
                  this.$message.error("删除失败");
                }
              })
              .catch(err => err);
          }
        })
        .catch(() => {
          return;
        });
    },
    //递归拉判断哪些叶子结点需要被默认选中
    getLeaf(node, arr) {
      if (!node.children) {
        // 这里要加return 目的是push 但是需要将递归终止
        return arr.push(node.id); //将id 传进去 因为绑定的node.keys是id用来标识那个叶子结点的
      }
      node.children.forEach(element => {
        this.getLeaf(element, arr);
      });
    },

    allocateRights(role) {
      this.roleId = role.id; //将id值记录 便于对话框使用
      this.checkList = []; //每次打开都需要清空
      this.getLeaf(role, this.checkList);
      // console.log(role)
      this.isVisiable = true;
      this.$http
        .get("rights/tree")
        .then(res => {
          if (res.data.meta.status == 200) {
            this.rightsList = res.data.data;
          } else {
            return;
          }
        })
        .catch(err => err);
    },
    //角色授权 根据点击的角色id获取被点击的权限的id提交到后台
    confirmAllocate() {
      let keys = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys()
      ];

      let keysString = keys.join(",");
      console.log(keysString);
      this.$http
        .post(`roles/${this.roleId}/rights`, {
          rids: keysString
        })
        .then(res => {
          console.log(res);
          if (res.data.meta.status == 200) {
            this.$message.success("添加成功");
            this.getRolesList();
          } else {
            this.$message.error("添加失败");
          }
        })
        .catch(err => err);
      this.isVisiable = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 20px;
}
// 列表展开的行的样式
.expand-row {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
.el-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
